//
//  XYComposeEmoticonCell.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/6.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit

class XYComposeEmoticonCell: UICollectionViewCell {
    
    private lazy var testLabel: UILabel = UILabel(textColor: UIColor.blackColor(), fontSize: 35)
    lazy var btns: [XYEmoticonBtn] = [XYEmoticonBtn]()
    var emoticons: [XYEmoticon]? {
        
        didSet {
            
            // 设置图片之前隐藏所有按钮
            for btn in btns {
                btn.hidden = true
            }
            for (i,emoticon) in emoticons!.enumerate() {
                
                let btn = btns[i]
                btn.hidden = false
                btn.emoticon = emoticon
            }
        }
    }
    
    var indexPath: NSIndexPath? {
        didSet {
            
            recentLabel.hidden = indexPath?.section != 0
            //            testLabel.text = "第\(indexPath!.section),第\(indexPath!.item)"
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    private func setUpUI() {
        contentView.addSubview(testLabel)
        contentView.addSubview(recentLabel)
        // 添加20 个按钮
        for _ in 0..<XYMaxEmoticonCountInPage {
            let btn = XYEmoticonBtn()
            btn.addTarget(self, action: "didClickEmoticon:", forControlEvents: UIControlEvents.TouchUpInside)
            btn.titleLabel?.font = UIFont.systemFontOfSize(36)
            contentView.addSubview(btn)
            btns.append(btn)
        }
        contentView.addSubview(deleteButton)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(contentView)
        }
        
        recentLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-5)
        }
        // 添加长按手势
        let ges = UILongPressGestureRecognizer(target: self, action: "didLongPressBtn:")
        addGestureRecognizer(ges)
        
    }
    @objc private func didLongPressBtn(ges:UIGestureRecognizer) {
        
        func buttonWithLocation(point:CGPoint) -> XYEmoticonBtn? {
            
            // 遍历frame  判断手指位置并返回btn
            for button in btns {
                if CGRectContainsPoint(button.frame, point) {
                    return button
                }
            }
            popView.removeFromSuperview()
            return nil
        }
        let currentPoint = ges.locationInView(self)
        
        guard let btn = buttonWithLocation(currentPoint) else {
            return
        }
        let state = ges.state
        switch state {
        case .Began, .Changed:
            let window = UIApplication.sharedApplication().windows.last
            let rect = btn.superview!.convertRect(btn.frame, toView: window)
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            // 设置数据
            popView.emoticon = btn.emoticon
            window?.addSubview(popView)
        case .Ended,.Cancelled:
            didClickEmoticon(btn)
            popView.removeFromSuperview()
        default:
            popView.removeFromSuperview()
        }
        
    }
    @objc private func didClickEmoticon(btn:XYEmoticonBtn) {
        
        
        NSNotificationCenter.defaultCenter().postNotificationName(XYDidClickEmoticonBtnNotification, object: nil, userInfo: ["emoticon": btn.emoticon!])
        XYEmoticonTool.sharedEmoticonTool.saveRecentEmoticon(btn.emoticon!)
        
        let emoticon = btn.emoticon
        popView.emoticon = emoticon
        let window = UIApplication.sharedApplication().windows.last!
        // 坐标系转换
        let rect = btn.superview!.convertRect(btn.frame, toView: window)
        // 计算pop的位置
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        window.addSubview(popView)
        // 0.25秒后移除
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.popView.removeFromSuperview()
        }
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let btnW = (self.frame.size.width - 10) / CGFloat(XYEmoticonMaxCol)
        let btnH = (self.frame.size.height - 20) / CGFloat(XYEmoticonMaxRow)
        for (i,btn) in btns.enumerate() {
            let col = i % XYEmoticonMaxCol
            let row = i / XYEmoticonMaxCol
            btn.frame = CGRect(x: CGFloat(col) * btnW, y: CGFloat(row) * btnH, width: btnW, height: btnH)
        }
        deleteButton.frame = CGRect(x: self.frame.width - btnW, y: self.frame.height - btnH, width: btnW, height: btnH)
    }
    // MARK: - 懒加载控件
    private lazy var recentLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.lightGrayColor()
        label.text = "最近使用的表情"
        return label
    }()
    
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        return button
    }()
    private lazy var popView: XYEmoticonPopView = XYEmoticonPopView.popView()
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
